import {
  Message,
  Notification
} from 'element-ui'
import {
  getToken
} from '@/utils/auth'
import store from '@/store'
import Vue from 'vue'
import Router from '@/router'
import {
  update
} from '@/api/mc/message'

let websock = null
let running = false
let initTimeout
let lockReconnect = false
let reconnectTimeout
const messageHandlers = []
const vue = new Vue()
let notification = null

var heartCheck = {
  timeout: 60000,
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function() {
    console.log('heart check start')
    // this赋值
    var self = this
    // 是否存在超时对象， 清空
    this.timeoutObj && clearTimeout(this.timeoutObj)
    // 是否存在超时对象， 清空
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
    this.timeoutObj = setTimeout(function() {
      console.log(websock, '连接实体')
      websock.send('ping')
      // self.serverTimeoutObj = setTimeout(function () {
      //   websock.close();
      // }, self.timeout);
    }, this.timeout)
  },
  stop: function() {
    this.timeoutObj && clearTimeout(this.timeoutObj)
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
  }
}

/**
 * 重新连接
 */
function reconnect() {
  if (!running || lockReconnect) {
    return
  }
  lockReconnect = true
  reconnectTimeout && clearTimeout(reconnectTimeout)
  reconnectTimeout = setTimeout(function() {
    initWebSocket()
    lockReconnect = false
  }, 5000)
}

/**
 * 初始化连接
 * @param token
 */
function init(token) {
  running = true
  if (websock === null) {
    const requstWsUrl = process.env.VUE_APP_WS + '/websocket/' + token
    try {
      websock = new WebSocket(requstWsUrl)
      // 连接错误
      websock.onerror = function(e) {
        console.error('websocket error')
        console.error(e)
        reconnect()
      }
      // 连接关闭
      websock.onclose = function(e) {
        console.log('websocket close , 关闭连接')
        console.log(e)
        reconnect()
      }
      // 建立连接
      websock.onopen = function() {
        console.log('websocket open')
        heartCheck.start()
      }
      // 获取信息
      websock.onmessage = function(e) {
        console.log('在此打印websocket的消息', e.data)
        heartCheck.start()
        if (e.data == 'pong') {
          console.log('socket message ' + e.data)
          return
        }
        let data
        try {
          data = JSON.parse(e.data)
        } catch (e) {
          data = e.data
        }
        if (data.type) {
          // 1 流程通过 2 流程拒绝
          if (data.type == 1) {
            const count = store.state.message.flowCount
            if (data.data == 1) {
              store.commit('message/FLOW_COUNT', parseInt(count) + 1)
            }
            store.commit('message/MESSAGE_COUNT', parseInt(store.state.message.messageCount) + 1)
            notification = Notification({
              duration: 0,
              title: '您有一条新消息',
              iconClass: 'el-icon-message',
              message: vue.$createElement('span', {
                style: {
                  color: 'red',
                  cursor: 'pointer'
                },
                on: {
                  click: () => goto(data.path, data.messageId)
                }
              }, data.remark),
              customClass: 'notifyStyle',
              position: 'bottom-right'
            })
          }
        }
      }
    } catch (e) {
      console.log(e,'rrrrrrrrr');
      console.error('init web socket error: ' + e)
      reconnect()
    }
  }
}

/**
 * 页面跳转
 * @param path
 * @param messageId
 */
function goto(path, messageId) {
  // 页面跳转关闭通知
  notification.close()

  const data = {
    messageId: messageId,
    status: 3
  }
  console.log(data, '修改为已读')
  update(data).then(res => {
    console.log(data, '修改为已读成功')
    Router.push(path)
    store.commit('message/MESSAGE_COUNT', parseInt(store.state.message.messageCount) - 1)
  })
}

/**
 * 初始化连接
 * @returns {boolean}
 */
export function initWebSocket() {
  if (typeof (WebSocket) === 'undefined') {
    Message.error('您的浏览器不支持WebSocket，无法获取数据')
    return false
  }

  const token = getToken()
  initTimeout && clearTimeout(initTimeout)
  if (token === undefined || token === null) {
    initTimeout = setTimeout(function() {
      initWebSocket()
    }, 5000)
  } else {
    init(token)
  }
}

/**
 * 关闭连接
 */
export function closeWebsocket() {
  running = false
  if (websock) {
    heartCheck.stop()
    websock.close()
    reconnectTimeout && clearTimeout(reconnectTimeout)
    lockReconnect = false
    websock = null
  }
}

/**
 * 添加信息请求头
 * @param type
 * @param handler
 * @returns {boolean}
 */
export function addMessageHanlder(type, handler) {
  if (type === undefined || type === null) {
    return false
  }
  if (handler === undefined || handler === null || typeof (handler) !== 'function') {
    return false
  }
  for (const i in messageHandlers) {
    if (type === messageHandlers[i].messageType) {
      messageHandlers.splice(i, 1)
      break
    }
  }
  messageHandlers.push({
    messageType: type,
    messageHandler: handler
  })
  return true
}

